<template>
  <div class="add-dept">
    <!-- 弹出框 -->
    <el-dialog :title="title" :visible="showDialog" @close="cancle">
      <!-- 表单结构 -->
      <el-form ref="myform" :rules="rules" :model="form" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code"></el-input>
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <!-- 选择器 -->
          <el-select v-model="form.manager" placeholder="请选择">
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="form.introduce"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getUserSimleApi } from "@/api/employees";
import { addDepartApi, updateDepartApi } from "@/api/departments";
export default {
  //showDialog: 对话框的显示与隐藏
  props: ["showDialog", "currentData", "type"],
  computed: {
    ...mapGetters(["depts"]),
    title() {
      return this.type == "add" ? "新增部门" : "编辑部门";
    }
  },
  data() {
    return {
      form: {
        name: "", //部门名称
        code: "", //部门编码唯一标识
        manager: "", //部门负责人
        introduce: "", //部门介绍
        pid: "" //父级部门id
      },
      userList: [], //负责人列表
      rules: {
        name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "1-50个字符", trigger: "blur" },
          {
            validator: async (rlue, value, callback) => {
              var bool;
              if (this.type == "add") {
                // 添加的验证规则 子部门的名称不能相同
                bool = this.depts
                  .filter(item => {
                    return item.pid == this.currentData.id; //筛选出选择项的子部门
                  })
                  .some(item => {
                    return item.name == value; //判断是否有同名
                  });
              } else {
                // 编辑的验证的规则
                bool = this.depts
                  .filter(item => {
                    return item.pid == this.currentData.id; //筛选出选择项的子部门
                  })
                  .some(item => {
                    return (
                      item.name == value && item.id !== this.currentData.id
                    );
                  });
              }
              bool ? callback(new Error("名称已存在")) : callback();
            }
          }
        ],
        code: [
          { required: true, message: "部门编码不能为空", trigger: "blur" },
          { min: 1, max: 300, message: "1-50个字符", trigger: "blur" },
          {
            validator: async (rule, value, callback) => {
              // 部门编码是所有部门的唯一标识
              var bool;
              if (this.type == "add") {
                bool = this.depts.some(item => {
                  return item.code == value;
                });
              } else {
                // 编辑规则
                bool = this.depts.some(item => {
                  return item.code === value && item.id !== this.currentData.id;
                });
              }
              bool ? callback(new Error("编码重复！")) : callback();
            }
          }
        ],
        manager: [
          { required: true, message: "部门负责人不能为空", trigger: "blur" }
        ],
        introduce: [
          { required: true, message: "部门介绍不能为空", trigger: "blur" },
          { min: 1, max: 300, message: "1-300个字符", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    closedialog() {
      this.$emit("closedialog");
    },

    // 得到所有负责人列表
    async getUserSimle() {
      let res = await getUserSimleApi();
      console.log(res);
      this.userList = res;
    },

    // 提交数据
    submit() {
      // 全局校验
      this.$refs.myform.validate(async isOk => {
        try {
          // 验证通过，发送请求到服务器
          if (this.type == "add") {
            // 添加提交
            let res = await addDepartApi({
              ...this.form,
              pid: this.currentData.pid == "-1" ? "" : this.currentData.id
            });
          } else {
            // 修改提交
            await updateDepartApi(this.form);
          }
          // 提示新增成功，父组件关闭面板
          this.$message.success("修改成功");
          this.$emit("closedialog", false);
          // 更新页面数据
          this.$emit("updatedata");
        } catch {
          console.log("新增失败");
          // 重置表单
          this.form = {
            name: "",
            code: "",
            manager: "",
            introduce: "",
            pid: ""
          };
        }
      });
    },

    // 取消按钮事件
    cancle() {
      // 重置表单验证规则
      this.$refs.myform.resetFields();
      this.$emit("update:showDialog", false);
      // 重置表单
      this.form = {
        name: "",
        code: "",
        manager: "",
        introduce: "",
        pid: ""
      };
    }
  },
  created() {
    // 得到所有的负责人列表
    this.getUserSimle();
  }
};
</script>

<style></style>
